<?php
/**
 * 把数组arr2合并到数组arr1中，相同的key以arr2中的为准，arr2中新增的key自动添加到arr1中
 *
 * @param  array $arr1
 * @param  array $arr2
 * @return array
 */
function array_merges($arr1, $arr2)
{
    foreach ($arr2 as $key => $val) {
        if (array_key_exists($key, $arr1) && is_array($val)) {
            if (array_keys($val) === range(0, count($val) - 1)) {
                $arr1[$key] = $arr2[$key];
            } else {
                $arr1[$key] = array_merges($arr1[$key], $arr2[$key]);
            }
        } else {
            $arr1[$key] = $val;
        }
    }
    return $arr1;
}

/**
 * 获取当前url
 *
 * @return string
 */
function getCurrentUrl()
{
    $url = 'http';
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') {
        $url .= "s";
    }
    $url .= "://";
    if ($_SERVER["SERVER_PORT"] != '80') {
        $url .= $_SERVER["HTTP_HOST"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $url .= $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
    }
    return $url;
}

/**
 * 字符串截取，支持中文和其他编码
 *
 * @param  string  $str [字符串]
 * @param  integer $start [起始位置]
 * @param  integer $length [截取长度]
 * @param  string  $charset [字符串编码]
 * @param  boolean $suffix [是否有省略号]
 * @return srting
 */
function mbSubStr($str, $start = 0, $length = 15, $charset = "utf-8", $suffix = true)
{
    if (function_exists("mb_substr")) {
        return mb_substr($str, $start, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
        return iconv_substr($str, $start, $length, $charset);
    }
    $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("", array_slice($match[0], $start, $length));
    if ($suffix) {
        return $slice . "…";
    }
    return $slice;
}

/**
 * 计算两个时间相差天数
 * <code>
 * $day = diffDay('2016-01-12', '2016-01-11');
 * echo "day is ", 1;
 * </code>
 *
 * @param  string $date1
 * @param  string $date2
 * @return int
 */
function diffDay($date1, $date2)
{
    return date_diff(date_create($date1), date_create($date2))->days;
}